package com.heima.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.media.dto.ChannelDto;
import com.heima.media.entity.WmChannel;
import com.heima.media.mapper.WmChannelMapper;
import com.heima.media.service.IWmChannelService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 频道信息表 服务实现类
 */
@Slf4j
@Service
public class WmChannelServiceImpl extends ServiceImpl<WmChannelMapper, WmChannel> implements IWmChannelService {

    /**
     * 根据名称模糊查询分页列表
     * @param channelDto
     * @return
     */
    @Override
    public ResponseResult listByName(ChannelDto channelDto) {
        // 当前页码，页码大小，模糊查询的字段
        Long page = channelDto.getPage();
        Integer size = channelDto.getSize();
        String name = channelDto.getName();

        // 判断接收数据是否为null
        if (channelDto==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE); // 缺少参数
        }

        // 条件构造器
        LambdaQueryWrapper<WmChannel> lambdaQueryWmChannel = Wrappers.lambdaQuery();
        if (StringUtils.isNotBlank(channelDto.getName())) {
            // 模糊查询
            lambdaQueryWmChannel.like(WmChannel::getName,name);
        }
        IPage<WmChannel> wmChannelIPage = new Page<>(page,size);
        IPage<WmChannel> pageInfo = this.page(wmChannelIPage, lambdaQueryWmChannel);
        //返回封装的数据
        return new PageResponseResult(page,size,pageInfo.getTotal(),pageInfo.getRecords());
    }

    /**
     * 频道新增
     * @param wmChannel
     * @return
     */
    @Override
    public ResponseResult saveChannel(WmChannel wmChannel) {
        // 判断接收数据是否为空
        if (wmChannel==null || StringUtils.isBlank(wmChannel.getName())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        // 条件构造器
        LambdaQueryWrapper<WmChannel> lambdaQueryWmChannel = Wrappers.lambdaQuery();
        lambdaQueryWmChannel.eq(WmChannel::getName, wmChannel.getName());
        if (this.count(lambdaQueryWmChannel)>0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST); //数据已存在
        }
        // 创建时间注意
        wmChannel.setCreatedTime(new Date());
        this.save(wmChannel);
        return ResponseResult.okResult();
    }

}
